<?php
/**
 * @Author: your name
 * @Date:   2017-05-19 10:30:34
 * @Last Modified by:   your name
 * @Last Modified time: 2017-07-17 09:57:54
 */
namespace app\index\controller;
use think\Controller;
//use Wx\Wechat;
class Wx extends Controller
{
    /**
     * 微信推送过来的数据或响应数据
     * @var array
     */
    private $data = array();
    /**
     * 主动发送的数据
     * @var array
    */
    private $send = array();
    private $token = 'lamidr';
    private $appid = 'wx30f182b53f2d32bb';
    private $AppSecret = 'fada8b5c75a55fadc1272bfa3cbd23ca';

    public function index($id = ''){
        //调试
        try{
            /*
            $appid = 'wx30f182b53f2d32bb'; //AppID(应用ID)
            $token = 'lamidr'; //微信后台填写的TOKEN
            $crypt = 'KWmR0ADkpGq5OIg80RTQlPh6AZ8kYLvZ7idR0ACKkgK'; //消息加密KEY（EncodingAESKey）
            $wechat =new \Wx\Wechat($token, $appid, $crypt);*/
            $wechat = wechat();
            /* 获取请求信息 */
            $data = $wechat->request();
            if($data && is_array($data)){
                //记录微信推送过来的数据
                //file_put_contents('./data.json', json_encode($data));
                $this->msg($wechat, $data);
            }
        } catch(\Exception $e){
            file_put_contents('./error.json', json_encode($e->getMessage()));
        }

    }


    /**
     * DEMO
     * @param  Object $wechat Wechat对象
     * @param  array  $data   接受到微信推送的消息
     */
    private function msg($wechat, $data){
        switch ($data['MsgType']) {
                    case 'event':
                        if($data['Event'] == 'subscribe'){
                            //$wechat->replyText("欢迎访问医药小伙伴");
                             logtxt('subscribe','subscribe');
                         }
                         if($data['Event'] == 'unsubscribe'){
                             logtxt('unsubscribe','unsubscribe');
                         }
                        break;
                    case Wechat::MSG_TYPE_TEXT :
                        logtxt('text',111);
                       // $wechat->replyText('欢迎您关注医药小伙伴^_^！');
                    break;

                    default:
                       //$wechat->replyText("欢迎访问医药小伙伴");
                        break;
                }
                break;
    }


    //获取微信AcessToken
     private function getAcessToken() {
        $appid = $this->appid;
        $appsecret = $this->AppSecret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token';
        $params = array ();
        $params ['grant_type'] = 'client_credential';
        $params ['appid'] = $appid;
        $params ['secret'] = $appsecret;
        $httpstr = http ( $url, $params );
        $harr = json_decode ( $httpstr, true );
        return $harr ['access_token'];
    }

    /**
     * 获取保存的token，没有重新请求
     */
    private function getToken() {
        $stoken = array ();
        $stoken = cache('S_TOKEN'); // 从缓存获取ACCESS_TOKEN
        if (!empty( $stoken )) {
            $nowtime = time ();
            $difftime = $nowtime - $stoken ['tokentime']; // 判断缓存里面的TOKEN保存了多久；
            if ($difftime > 3600) { // TOKEN有效时间7200 判断超过7000就重新获取;
                $accesstoken = $this->getAcessToken (); // 去微信获取最新ACCESS_TOKEN
                $stoken ['tokentime'] = time ();
                $stoken ['token'] = $accesstoken;
                cache('S_TOKEN', $stoken, 3600);//设置缓存
            } else {
                $accesstoken = $stoken ['token'];
            }
        } else {
            $accesstoken = $this->getAcessToken (); // 去微信获取最新ACCESS_TOKEN
            $stoken ['tokentime'] = time ();
            $stoken ['token'] = $accesstoken;
            cache('S_TOKEN', $stoken, 3600); // 放进缓存
        }

        return $accesstoken;
    }

    /**
     * 创建自定义菜单
     */
    public function createMenu() {
        $token = $this->getToken();
        $menu = $this->getMenu();
        $data = json_encode($menu,JSON_UNESCAPED_UNICODE);
        $url = 'https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.$token;
        $reponse=http($url,$data,'POST');
        return $reponse;
    }

    /**
     * 菜单
     */
    private function getMenu(){
        $button = [];
        $parent = db('button')->where('pid',0)->field('id,pid,name')->select();
        $son = db('button')->where('pid','gt',0)->select();
        foreach ($parent as $k => $v) {
            foreach ($son as $key => $val) {
                if($val['pid'] == $v['id']){
                    $parent[$k]['sub_button'][] = array(
                        'name'=>$val['name'],
                        'type'=>$val['type'],
                        'url'=>$val['url']
                        );

                }
            }
            unset($parent[$k]['pid']);
            unset($parent[$k]['id']);
        }
        $button['button'] = $parent;
        return $button;
    }


    public function aa(){
        echo 111;
        logtxt('s',11);
    }











}